package com.ywz.framework.mybatisplus;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ywz.project.base.system.entity.TTenement;
import com.ywz.project.base.system.service.TTenementService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

/**
 * 类描述 -> 启动系统时初始化数据库配置
 *
 * @Author: ywz
 * @Date: 2024/11/17
 */
@Component
public class CommandLineRunnerService implements CommandLineRunner {
    @Resource
    private TTenementService tTenementService;
    @Resource
    private DataSource dataSource;
    @Resource
    private DefaultDataSourceCreator dataSourceCreator;
    @Value("${tenement.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${tenement.datasource.url-suffix}")
    private String urlSuffix;

    @Override
    public void run(String... args) {
        System.out.println("==================初始化租户数据库配置==================");
        LambdaQueryWrapper<TTenement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TTenement::getIsDeleted, 0);
        List<TTenement> list = tTenementService.list(wrapper);
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        for (TTenement tTenement : list) {
            // 配置数据源
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setLazy(true);
            dataSourceProperty.setUsername(tTenement.getDbUsername());
            dataSourceProperty.setPassword(tTenement.getDbPassword());
            String url = tTenement.getDbUrl();
            if (!url.contains(":"))
                url = url + ":3306"; // 使用默认端口号
            dataSourceProperty.setUrl("jdbc:mysql://" + url + "/saas-crm-" + tTenement.getTenantKey() + urlSuffix);
            dataSourceProperty.setDriverClassName(driverClassName);
            ds.addDataSource(tTenement.getTenantKey(), dataSourceCreator.createDataSource(dataSourceProperty));
        }
    }
}
